package com.easy.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.WxMaUserService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.hutool.core.util.ObjectUtil;
import com.easy.common.api.CommonResult;
import com.easy.common.exception.Asserts;
import com.easy.config.WxMaConfiguration;
import com.easy.domain.User;
import com.easy.domain.UserLoginPojo;
import com.easy.service.SessionService;
import com.easy.service.UserService;
import io.netty.util.internal.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

/**
 * @author 风亦未止
 * @date 2021/9/20 16:59
 */
@Api(tags = "用户相关接口")
@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private HttpSession httpSession;

    @Autowired
    private UserService userService;

    @Autowired
    private SessionService sessionService;

    @Value("${wxappid}")
    private String appid;

    @ApiOperation(value = "用户登录")
    @PostMapping("/login")
    public CommonResult login(@RequestBody UserLoginPojo userLoginPojo){
        if (StringUtil.isNullOrEmpty(userLoginPojo.getJsCode())){
            Asserts.fail("用户jsCode不能为空！");
        }
        WxMaJscode2SessionResult sessionInfo = null;
        try {
            WxMaService maService = WxMaConfiguration.getMaService(appid);
            WxMaUserService userMaService = maService.getUserService();
            sessionInfo = userMaService.getSessionInfo(userLoginPojo.getJsCode());
        } catch (WxErrorException e) {
            Asserts.fail("用户jsCode无效！");
        }
        String openid = sessionInfo.getOpenid();
        //sessionKey好像没啥用
        String sessionKey = sessionInfo.getSessionKey();
        User user = userService.lambdaQuery().eq(User::getOpenid, openid).one();
        //如果用户未注册过
        if (ObjectUtil.isNull(user)){
            //直接注册一个新的用户
            user = new User();
            user.setOpenid(openid);
            user.setNickName(userLoginPojo.getNickName()!=null?userLoginPojo.getNickName():null);
            user.setAvatarUrl(userLoginPojo.getUserAvatarUrl()!=null?userLoginPojo.getUserAvatarUrl():null);
            userService.save(user);
        }else{
            //更新信息
            user.setAvatarUrl(userLoginPojo.getUserAvatarUrl()!=null?userLoginPojo.getUserAvatarUrl():null);
            user.setNickName(userLoginPojo.getNickName()!=null?userLoginPojo.getNickName():null);
            userService.updateById(user);
        }
        //保存session
        String sessionId = httpSession.getId();
        sessionService.setSession(sessionId,user);
        return CommonResult.success(sessionId,"登录成功！");
    }

//    @ApiOperation(value = "用户登录")
//    @PostMapping("/login")
    public CommonResult login(@RequestParam("openid") @ApiParam(value = "用户openid") String openid,
                               @RequestParam("nickName") @ApiParam(value = "用户头像") String nickName,
                               @RequestParam("avatarUrl") @ApiParam(value = "用户头像") String avatarUrl){
        if (StringUtil.isNullOrEmpty(openid.trim())){
            Asserts.fail("用户openid不能为空！");
        }
        User user = userService.lambdaQuery().eq(User::getOpenid, openid).one();
        //如果用户未注册过
        if (ObjectUtil.isNull(user)){
            //直接注册一个新的用户
            user = new User();
            user.setOpenid(openid);
            user.setNickName(nickName!=null?nickName:null);
            user.setAvatarUrl(avatarUrl!=null?avatarUrl:null);
            userService.save(user);
        }else{
            //更新信息
            user.setNickName(nickName!=null?nickName:null);
            user.setAvatarUrl(avatarUrl!=null?avatarUrl:null);
            userService.updateById(user);
        }
        //保存session
        String sessionId = httpSession.getId();
        sessionService.setSession(sessionId,user);
        return CommonResult.success(sessionId,"登录成功！");
    }


}
